;;; config.scm --- Configuration module for Guile-XOSD

;; Copyright © 2016 Alex Kost <alezost@gmail.com>

;; This file is part of Guile-XOSD.

;; Guile-XOSD is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;;
;; Guile-XOSD is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with Guile-XOSD.  If not, see <http://www.gnu.org/licenses/>.

;;; Commentary:

;; This module provides configuration variables for guile-xosd.

;;; Code:

(define-module (xosd config)
  #:use-module (ice-9 regex)
  #:use-module (srfi srfi-26)
  #:export (%documentation-file-name
            %library-name
            %library-directory
            %library-file-name))

;; This code of 'config-lookup' (modified a bit) is taken from
;; <http://git.savannah.gnu.org/cgit/guix.git/tree/scripts/guix.in>.
(define (config-lookup variable)
  "Return the value of the compile-time VARIABLE.
Finding such values is not trivial, as they may be recursive.  For
example, default value of 'libdir' is '${exec_prefix}/lib', so we need
to find out the value of 'exec_prefix' at first, etc."
  (define config
    '(("prefix"         . "@prefix@")
      ("exec_prefix"    . "@exec_prefix@")
      ("guilemoduledir" . "@guilemoduledir@")
      ("libdir"         . "@libdir@")))

  (define var-ref-regexp (make-regexp "\\$\\{([a-z_]+)\\}"))

  (define (expand-var-ref match)
    (config-lookup (match:substring match 1)))

  (define (expand str)
    (regexp-substitute/global #f var-ref-regexp str
                              'pre expand-var-ref 'post))

  (define (lookup name)
    (expand (assoc-ref config name)))

  (lookup variable))

(define %library-name
  "@LIBRARY_NAME@")

(define %library-directory
  (or (getenv "GUILE_XOSD_LIBDIR")
      (config-lookup "libdir")))

;; File name of the library without extension.
(define %library-file-name
  (string-append %library-directory "/" %library-name))

;; File with documentation for Guile procedures.
(define %documentation-file-name
  (string-append (or (getenv "GUILE_XOSD_DOCDIR")
                     (config-lookup "guilemoduledir"))
                 "/xosd-procedures.txt"))

;;; config.scm ends here
